package com.fmatos.amazingwallpapers.downloader;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.app.WallpaperManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import com.fmatosqg.gatherimages.backgroundmanager.BackgroundManager;
import com.fmatosqg.gatherimages.configuration.DownloaderConfiguration;
import com.fmatosqg.gatherimages.downloader.utils.DownloaderRuntimeException;

public class BackgroundManagerForAndroid implements BackgroundManager {

	private final Context mContext;
	
	public BackgroundManagerForAndroid(Context mContext) {
		super();
		this.mContext = mContext;
	}

	
	public String getGalleryFolderPath() {
		
		File folder = mContext.getFilesDir();

		testWriting(folder);
		return folder.getPath();
	}
	
	private void testWriting(File folder) {
		
		FileOutputStream fos = null;

		try {
			fos = new FileOutputStream(new File(folder,"test.txt"));
			
			fos.write("tesstttt".getBytes());
			fos.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			Log.e("Tutorial", "could not write to folder " + folder.getAbsolutePath());
		} catch (IOException e) {
			e.printStackTrace();
		}

		finally {
			try {
				if (fos != null) {
					fos.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
	}

	public boolean setBackgroundImageFromUrl(String url,
			DownloaderConfiguration config)  {
		throw new DownloaderRuntimeException("Not coded yet");
//		return false;
	}

	public boolean setBackgroundImage(String filePath) {
		// TODO Auto-generated method stub
		
		
			WallpaperManager m=WallpaperManager.getInstance(mContext);

			try { 
				Bitmap bmap = loadImageFromCache(filePath);
				m.setBitmap(bmap );
			} catch (IOException e) {
				e.printStackTrace();
			}
		
		return true;
//		throw new DownloaderRuntimeException("Not coded yet"); 
//		return false;
	}

	// move this to a separate class
	@Deprecated
	private Bitmap loadImageFromCache(String filePath) {

		InputStream is;
		Bitmap bm =null;
		try {
			is = new FileInputStream(filePath);
			BufferedInputStream bis = new BufferedInputStream(is);
			bm = BitmapFactory.decodeStream(bis);
			is.close();

		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		if ( bm == null) {
			Log.i("Tutorial", "Couldn't get bitmap for file " + filePath);
		}
		return bm;
	}

}
